package org.ispider.tweets;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.*;

import org.codehaus.groovy.grails.web.json.JSONArray;
import org.codehaus.groovy.grails.web.json.JSONObject;
import org.ispider.Utils;
import org.ispider.tweets.TweetInfo;

public class FetchTweetsJson {
	private String queryParam = "nexus";
	private StringBuffer tweetSearchURL = new StringBuffer();
	private String response = new String();

	/**
	 * @param args
	 */
	public static ArrayList<TweetInfo> getTwitterData(String query) {
		FetchTweetsJson tw = new FetchTweetsJson();
		tw.queryParam = query.replaceAll("\\s", "+");
		tw.tweetSearchURL
				.append("http://search.twitter.com/search.json?q="
						+ tw.queryParam
						+ "&include_rts=1&lang=en&geocode=%2221.125498,79.057617,2000km%22");
		try {
			tw.response = tw.readUrl(tw.tweetSearchURL.toString());
		} catch (Exception e) {
			e.printStackTrace();
		}
		return (tw.parseTweets(tw.response));
	}

	private String readUrl(String urlString) throws Exception {
		StringBuilder response = new StringBuilder();

		URL url = new URL(urlString);
		HttpURLConnection httpconn = (HttpURLConnection) url.openConnection();
		if (httpconn.getResponseCode() == HttpURLConnection.HTTP_OK) {
			BufferedReader input = new BufferedReader(new InputStreamReader(
					httpconn.getInputStream()), 8192);
			String strLine = null;
			while ((strLine = input.readLine()) != null) {
				response.append(strLine);
			}
			input.close();
		}
		return response.toString();
	}

	private ArrayList<TweetInfo> parseTweets(String response) {
		ArrayList<TweetInfo> tweetInfo = new ArrayList<TweetInfo>();
		JSONObject object = new JSONObject(response);
		JSONArray array = object.getJSONArray("results");
		for (int i = 0; i < array.length(); i++) {
			try {
				TweetInfo tw = new TweetInfo();
				String text = array.getJSONObject(i).getString("text");
				
				String fromUser = array.getJSONObject(i).getString("from_user");
				if (fromUser != null) {
					tw.setFromUser(fromUser);
				} else {
					tw.setFromUser(" ");
				}
				String createdAt = array.getJSONObject(i).getString(
						"created_at");

				if (createdAt != null) {
					tw.setCreatedTime(createdAt);
				} else {
					tw.setCreatedTime(" ");
				}
				String location = array.getJSONObject(i).getString("location");
				if (location != null) {
					tw.setLocation(location);
				} else {
					tw.setLocation(" ");
				}

				String id = array.getJSONObject(i).getString("id_str");
				tw.setTweetID(id);
				String urlString = " http://www.twitter.com/"
						+ tw.getFromUser() + "/status/" + id;
				tw.setUrlString(urlString);
				if (text != null) {

					String[] keywords = queryParam.split("\\+");
					for (String s : keywords)
						text = text.replaceAll("(?i)" + s, "<b>" + s + "</b>");
					tw.setText(Utils.makeLinks(text,urlString));
				}
				String picture = array.getJSONObject(i).getString(
						"profile_image_url");
				tw.setPicture(picture);
				String userURLString = "http://www.twitter.com/"
						+ tw.getFromUser();
				tw.setUserURLString(userURLString);
				tweetInfo.add(tw);
			} catch (Exception e) {

			}

		}
		return tweetInfo;

	}
}
